﻿using System;
using System.Collections;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Torch.WL.Business;
using Torch.FrameWork.Utility;



namespace Torch.WL.Web.Admin.Modubles
{
    public partial class RolesAuthorizedPage : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           
            strinfo.InnerHtml = "";
            strinfo.Visible = false;
            if (!IsPostBack)
            {               
                //初始化模块权限
                UserHandle.InitModule("admin_RolesAuthorizedPage");
                if (UserHandle.ValidationHandle(PermissionTag.Browse))//是否有浏览权限
                {
                    BindGroups();
                    BindModuleType("0", 0);
                    BindRoles();
                }
                else
                {
                    GotoErrPage("无权限!");
                }

            }
        }

        /// <summary>
        /// 获取角色列表
        /// </summary>
        protected void BindRoles()
        {
            RoleLogic Rolsebll = new RoleLogic();
            DataSet ds = Rolsebll.GetRoleList("RoleGroupID=" + GroupList.SelectedValue, "");
            RoleView.DataSource = ds;
            RoleView.DataBind();
        }

        /// <summary>
        /// 获取模块权限列表
        /// </summary>
        protected void BindModules()
        {
            if (Rid.Text != "")
            {
                ModuleLogic Mbll = new ModuleLogic();
                DataSet ds = Mbll.GetModuleList2(ModuleTypeList.SelectedValue);
                ModuleView.DataSource = ds;
                ModuleView.DataBind();

                if (ds.Tables[0].Rows.Count == 0)
                {
                    btn_AllSave.Visible = false;
                }
                else
                {
                    if (UserHandle.ValidationHandle(PermissionTag.Grant))
                    {
                        btn_AllSave.Visible = true;
                    }
                    else
                    {
                        btn_AllSave.Visible = false;
                    }
                }
            }
            else
            {
                btn_AllSave.Visible = false;
                ModuleView.DataSource = null;
                ModuleView.DataBind();
            }

        }

        /// <summary>
        /// 绑定分组数据
        /// </summary>
        protected void BindGroups()
        {
            GroupLogic Groupbll = new GroupLogic();
            DataSet ds = Groupbll.GetGroupList("GroupType=1", "order by GroupOrder asc");

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                string s = ds.Tables[0].Rows[i]["GroupName"].ToString();

                GroupList.Items.Add(new ListItem(s, ds.Tables[0].Rows[i]["GroupID"].ToString()));

            }
        }

        /// <summary>
        /// 加载分类
        /// </summary>
        /// <param name="MtID">分类上级ID</param>
        /// <param name="Depth">分类级别深度</param>
        /// <param name="flag">指定分类组件</param>
        protected void BindModuleType(string MtID, int Depth)
        {
            ModuleLogic MTbll = new ModuleLogic();
            DataView dvList = new DataView(MTbll.GetModuleTypeList("").Tables[0]);
            dvList.RowFilter = "ModuleTypeSuperiorID=" + MtID;  //过滤父节点 
            foreach (DataRowView dv in dvList)
            {
                string depth = string.Empty;
                for (int i = 0; i < Depth; i++)
                {
                    depth = depth + "-";
                }

                ModuleTypeList.Items.Add(new ListItem(depth + dv["ModuleTypeName"].ToString(), dv["ModuleTypeID"].ToString()));
                BindModuleType(dv["ModuleTypeID"].ToString(), int.Parse(dv["ModuleTypeDepth"].ToString()) + 1);  //递归 
            }
        }

        /// <summary>
        /// 查看角权限
        /// </summary>
        protected void RoleView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.ToString() == "EditView")
            {
                //HtmlInputHidden hidRoleID = (HtmlInputHidden)this.RoleView.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("hidRoleID");
                //Literal ltCurrent = (Literal)this.RoleView.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("hidRoleID");

                Rid.Text = e.CommandArgument.ToString(); 

                if (!ModuleTypeList.Enabled)
                    ModuleTypeList.Enabled = true;
                //int.Parse(e.CommandArgument.ToString());

                BindModules();

                foreach (GridViewRow gvr in RoleView.Rows)
                {
                    LinkButton lbtn_name = (LinkButton)gvr.FindControl("lbtn_name");
                    if (lbtn_name.CssClass == "CurrentSelected")                    
                    {
                        lbtn_name.CssClass = "";
                    }                    
                }
                
                ((LinkButton)e.CommandSource).CssClass = "CurrentSelected";
               
            }
        }

        /// <summary>
        /// 根据分组排序角色
        /// </summary>
        protected void GroupList_SelectedIndexChanged(object sender, EventArgs e)
        {
            Rid.Text = "";
            ModuleTypeList.Enabled = false;
            BindRoles();
            BindModules();
        }

        /// <summary>
        /// 根据模块分类排序模块
        /// </summary>
        protected void ModuleTypeList_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindModules();
        }

        /// <summary>
        /// 模块分类数据绑定
        /// </summary>
        protected void ModuleView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                AuthorityDirLogic AD = new AuthorityDirLogic();
                ModuleLogic Modulebll = new ModuleLogic();
                RoleLogic Rolebll = new RoleLogic();

                Repeater rptAuthrityList = (Repeater)e.Row.FindControl("rptAuthrityList");
                Label lab_ID = (Label)e.Row.FindControl("lab_ID");
                Label lab_Verify = (Label)e.Row.FindControl("lab_Verify");

                ////取该模块的权限列表, 不把所有权限取出来
                //DataSet ds = AD.GetAuthorityList("", "order by AuthorityOrder asc");
                DataSet ds = Modulebll.GetAuthorityNameList(int.Parse(lab_ID.Text));

                DataSet MALDS = Modulebll.GetAuthorityList(int.Parse(lab_ID.Text));
                DataSet RALDS = Rolebll.GetRoleAuthorityList(int.Parse(Rid.Text), int.Parse(lab_ID.Text));
               
                DataTable dtTypeNameList = ds.Tables[0].DefaultView.ToTable(true, "TypeName");
                rptAuthrityList.DataSource = dtTypeNameList;
                rptAuthrityList.DataBind();

                int n = ds.Tables[0].Rows.Count;//系统权限个数
                string[] vstate = new string[n];

                int nowPos = 0;

                for (int j = 0; j < rptAuthrityList.Items.Count; j++)
                {
                    CheckBoxList AuthorityList_Grant = (CheckBoxList)rptAuthrityList.Items[j].FindControl("AuthorityList_Grant");
                    Literal ltlTypeName = (Literal)rptAuthrityList.Items[j].FindControl("ltlTypeName");
                    AuthorityList_Grant.Items.Clear();

                    DataRow[] drsByTypeName = ds.Tables[0].Select(string.Format("TypeName='{0}'", ltlTypeName.Text.Trim()));

                    //获取系统配置的权限列表，如果模块没有该权限，则禁用该权限
                    for (int i = 0; i < drsByTypeName.Length; i++)
                    {
                        AuthorityList_Grant.Items.Add(new ListItem(drsByTypeName[i]["AuthorityName"].ToString(), drsByTypeName[i]["AuthorityTag"].ToString()));
                        AuthorityList_Grant.Items[i].Enabled = false;

                        if (MALDS.Tables[0].Select(string.Format("AuthorityTag='{0}'", drsByTypeName[i]["AuthorityTag"].ToString())).Length > 0)
                        {
                            AuthorityList_Grant.Items[i].Enabled = true;
                        }
                        vstate[nowPos + i] = "0";//初始状态数组; 未选中
                    }

                    AuthorityList_Grant.DataBind();

                    //将模块权限付值
                    for (int l = 0; l < AuthorityList_Grant.Items.Count; l++)
                    {
                        if (Contains(RALDS.Tables[0], AuthorityList_Grant.Items[l].Value))
                        {
                            if (AuthorityList_Grant.Items[l].Enabled)
                                vstate[nowPos + l] = "1";//选中

                            //权限允许
                            AuthorityList_Grant.Items[l].Selected = true;
                        }
                    }

                    nowPos += drsByTypeName.Length - 1;
                }

                if (vstate.Length > 0)
                    lab_Verify.Text = TypeParse.StringArrayToString(vstate, ',');
                else
                    lab_Verify.Text = "";

                if (!UserHandle.ValidationHandle(PermissionTag.Grant))//是否有编辑权限
                {
                    ModuleView.Columns[2].Visible = false;
                }

            }
        }

        bool Contains(DataTable list, string tag)
        {
            return list.Select(string.Format("Flag=1 and AuthorityTag='{0}'", tag.ToUpper())).Length > 0;

        }

        /// <summary>
        /// 保存所有修改的权限
        /// </summary>
        protected void btn_AllSave_Click(object sender, EventArgs e)
        {
            RoleLogic Rolebll = new RoleLogic();

            ArrayList list = new ArrayList();//建立事务列表
            for (int i = 0; i <= ModuleView.Rows.Count - 1; i++)
            {
                Label lab_Verify = (Label)this.ModuleView.Rows[i].Cells[0].FindControl("lab_Verify");
                string[] vstate = lab_Verify.Text.Split(',');//获取原始状态
                Repeater rptAuthrityList = (Repeater)this.ModuleView.Rows[i].FindControl("rptAuthrityList");
                int nowPos = 0;

                for (int jj = 0; jj < rptAuthrityList.Items.Count; jj++)
                {
                    CheckBoxList cal = (CheckBoxList)rptAuthrityList.Items[jj].FindControl("AuthorityList_Grant");
                    for (int j = 0; j < cal.Items.Count; j++)
                    {
                        if (cal.Items[j].Enabled)
                        {
                            if (cal.Items[j].Selected)
                            {
                                if (vstate[j + nowPos] != "1")//检查数据有没有变化
                                {
                                    string item = string.Empty;
                                    item = item + Rid.Text + "|"
                                        + this.ModuleView.DataKeys[i].Values[0].ToString() + "|"
                                        + cal.Items[j].Value + "|1";//设置为1，加入权限
                                    list.Add(item);
                                }
                            }
                            else
                            {
                                if (vstate[j + nowPos] != "0")//检查数据有没有变化
                                {
                                    string item = string.Empty;
                                    item = item + Rid.Text + "|"
                                        + this.ModuleView.DataKeys[i].Values[0].ToString() + "|"
                                        + cal.Items[j].Value + "|0";//设置为0，删除删除
                                    list.Add(item);
                                }
                            }
                        }
                    }
                    nowPos += cal.Items.Count - 1;
                }
            }

            if (Rolebll.UpdateRoleAuthority(list))
            {
                BindModules();
                ShowMsg(true, "设置成功！");    
            }
            else
            {
                ShowMsg(true, "设置操作失败！");
            }
        }

        /// <summary>
        /// 更新设置
        /// </summary>
        protected void ModuleView_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            ArrayList list = new ArrayList();//建立事务列表
            RoleLogic Rolebll = new RoleLogic();
            Repeater rptAuthrityList = (Repeater)this.ModuleView.Rows[e.NewSelectedIndex].FindControl("rptAuthrityList");

            Label lab_Verify = (Label)this.ModuleView.Rows[e.NewSelectedIndex].Cells[0].FindControl("lab_Verify");

            string[] vstate = lab_Verify.Text.Split(',');//获取原始状态

            int nowPos = 0;

            for (int j = 0; j < rptAuthrityList.Items.Count; j++)
            {
                CheckBoxList cal = (CheckBoxList)rptAuthrityList.Items[j].FindControl("AuthorityList_Grant");

                for (int i = 0; i < cal.Items.Count; i++)
                {
                    if (cal.Items[i].Enabled)
                    {
                        if (cal.Items[i].Selected)
                        {
                            if (vstate[i + nowPos] != "1")//检查数据有没有变化
                            {
                                string item = string.Empty;
                                item = item + Rid.Text + "|"
                                    + this.ModuleView.DataKeys[e.NewSelectedIndex].Values[0].ToString() + "|"
                                    + cal.Items[i].Value + "|1";//设置为1，加入权限
                                list.Add(item);
                            }
                        }
                        else
                        {
                            if (vstate[i + nowPos] != "0")//检查数据有没有变化
                            {
                                string item = string.Empty;
                                item = item + Rid.Text + "|"
                                    + this.ModuleView.DataKeys[e.NewSelectedIndex].Values[0].ToString() + "|"
                                    + cal.Items[i].Value + "|0";//设置为0，删除删除
                                list.Add(item);
                            }
                        }
                    }
                }

                nowPos += cal.Items.Count - 1;
            }

            if (Rolebll.UpdateRoleAuthority(list))
            {
               
                BindModules(); 
                ShowMsg(true, "更新成功！");                
            }
            else
            {
                ShowMsg(true, "更新失败！");  
            }
        }

        void ShowMsg(bool success, string msg)
        {
            strinfo.InnerHtml = msg;
            strinfo.Attributes["class"] = success ? "w_info" : "w_error";
            strinfo.Visible = true;
        }
    }


}
